import { renderToString } from 'react-dom/server';
import styles from './banner.less';
import { Swiper, SwiperSlide } from 'swiper/react/swiper-react';
import { EffectFade, Pagination, Autoplay, Lazy } from 'swiper';
import _ from 'lodash';
import { useDispatch, useSelector } from 'umi';
import { useEffect } from 'react';
import { Spin } from 'antd';
import 'swiper/swiper-bundle.css';
import 'swiper/modules/pagination/pagination.less';
import 'swiper/modules/navigation/navigation.less';
import 'swiper/modules/autoplay/autoplay.less';

const Banner = () => {
  const dispatch = useDispatch();

  const state = useSelector((state: any) => ({
    data: state.banner.banner_list,
    loading: state.loading.models.banner || false,
  }));

  useEffect(() => {
    dispatch({
      type: 'banner/getBannerList',
    });
  }, []);

  const swiperProps: any = {
    onSwiper: (swiper: any) => {
      setTimeout(() => {
        swiper.lazy.load();
      }, 100);

      swiper.el.onmouseover = () => {
        swiper.autoplay.stop();
      };
      swiper.el.onmouseout = () => {
        swiper.autoplay.start();
      };
    },
    className: styles.banner,
    loop: true,
    modules: [EffectFade, Pagination, Autoplay, Lazy],
    effect: 'fade',
    autoplay: {
      delay: 2000,
      pauseOnMouseEnter: true,
    },
    pagination: {
      clickable: true,
      bulletClass: styles.pagination_item,
      bulletActiveClass: styles.pagination_item_active,
      renderBullet: (index: number, className: string) => {
        let text = '';
        switch (index) {
          case 0:
            text = '必品阁买一增一';
            break;
          case 1:
            text = '民生食品 抗疫保供';
            break;
          case 2:
            text = '早春味道';
            break;
          case 3:
            text = '官方微信 限时福利';
            break;
          case 4:
            text = '本来生活韩国馆';
            break;
          case 5:
            text = '热情火锅节';
            break;
        }
        return renderToString(<span className={`${className}`}>{text}</span>);
      },
    },
    lazy: {
      loadPrevNext: true,
    },
  };
  return (
    <Spin spinning={state.loading}>
      <Swiper {...swiperProps}>
        {_.map(state.data, (item, key: number) => {
          const obj: any = {
            'data-background': item.img,
          };
          return (
            <SwiperSlide key={item.id}>
              <a {...obj} className="swiper-lazy">
                <div className="swiper-lazy-preloader"></div>
              </a>
            </SwiperSlide>
          );
        })}
      </Swiper>
    </Spin>
  );
};

export default Banner;
